package com.ls.fw.data.search.impl.solrj.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import net.sf.json.JSONObject;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

public class HttpUtil {

	public static JSONObject get(String url) throws IOException{
		HttpClient httpclient =  new DefaultHttpClient();
    	HttpGet httpGet = new HttpGet(url);
        HttpResponse response;
		try {
			response = httpclient.execute(httpGet);
		} catch (ClientProtocolException e) {
			throw e;
		} catch (IOException e) {
			throw e;
		}
        JSONObject json = new JSONObject();
        if(response.getStatusLine().getStatusCode()==200){
        	HttpEntity entity = response.getEntity();
        	if (entity != null) {
        		InputStream instream = null;
        		try {
        			instream = entity.getContent();
        			BufferedReader reader = new BufferedReader(
        					new InputStreamReader(instream));
        			String str = null;
        			StringBuffer sb = new StringBuffer();
        			while((str = reader.readLine())!=null){
        				sb.append(str);
        			}
        			json = JSONObject.fromObject(sb.toString());
        		} catch (IOException ex) {
        			throw ex;
        		} catch (RuntimeException ex) {
        			httpGet.abort();
        			throw ex;
        		} finally {
        			if(instream!=null){
        				instream.close();
        			}
        		}
        		httpclient.getConnectionManager().shutdown();
            }
        }
        return json;
	}
                
}
